package io.finer.erp.jeecg.bas.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import io.finer.erp.jeecg.bas.entity.BasCategoryLabel;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasSupplier;
import io.finer.erp.jeecg.bas.model.TreeModel;
import io.finer.erp.jeecg.bas.service.IBasCategoryLabelService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasSupplierService;
import io.finer.erp.jeecg.bas.vo.CategoryLabelVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 物料分类
 * @Author: jeecg-boot
 * @Date:   2020-05-29
 * @Version: V1.0
 */
@Api(tags="物料分类")
@RestController
@RequestMapping("/bas/basMaterialCategory")
@Slf4j
public class BasMaterialCategoryController extends JeecgController<BasMaterialCategory, IBasMaterialCategoryService>{
	@Autowired
	private IBasMaterialCategoryService basMaterialCategoryService;
	@Autowired
	private IBasSupplierService supplierService;
	@Autowired
	private IBasCategoryLabelService labelService;
	
	/**
	 * 分页列表查询
	 *
	 * @param basMaterialCategory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "物料分类-分页列表查询")
	@ApiOperation(value="物料分类-分页列表查询", notes="物料分类-分页列表查询")
	@GetMapping(value = "/rootList")
	public Result<?> queryPageList(BasMaterialCategory basMaterialCategory,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BasMaterialCategory> queryWrapper = QueryGenerator.initQueryWrapper(basMaterialCategory, req.getParameterMap());
		Page<BasMaterialCategory> page = new Page<BasMaterialCategory>(pageNo, pageSize);
		IPage<BasMaterialCategory> pageList = basMaterialCategoryService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 /**
      * 获取子数据
      * @param testTree
      * @param req
      * @return
      */
	@AutoLog(value = "物料分类-获取子数据")
	@ApiOperation(value="物料分类-获取子数据", notes="物料分类-获取子数据")
	@GetMapping(value = "/childList")
	public Result<?> queryPageList(BasMaterialCategory basMaterialCategory,HttpServletRequest req) {
		QueryWrapper<BasMaterialCategory> queryWrapper = QueryGenerator.initQueryWrapper(basMaterialCategory, req.getParameterMap());
//		List<BasMaterialCategory> list = basMaterialCategoryService.list(queryWrapper);
		Page<BasMaterialCategory> page = new Page<BasMaterialCategory>(1, 300);
		IPage<BasMaterialCategory> pageList = basMaterialCategoryService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	
	/**
	 *   添加
	 *
	 * @param basMaterialCategory
	 * @return
	 */
	@AutoLog(value = "物料分类-添加")
	@ApiOperation(value="物料分类-添加", notes="物料分类-添加")
	@PostMapping(value = "/add")
	@CacheEvict(value= {CacheConstant.SYS_DICT_TABLE_CACHE,CacheConstant.BAS_MATERIAL_CATEGORY}, allEntries=true)
	public Result<?> add(@RequestBody BasMaterialCategory basMaterialCategory) {
		basMaterialCategoryService.addBasMaterialCategory(basMaterialCategory);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param basMaterialCategory
	 * @return
	 */
	@AutoLog(value = "物料分类-编辑")
	@ApiOperation(value="物料分类-编辑", notes="物料分类-编辑")
	@PutMapping(value = "/edit")
	@CacheEvict(value= {CacheConstant.SYS_DICT_TABLE_CACHE,CacheConstant.BAS_MATERIAL_CATEGORY}, allEntries=true)
	public Result<?> edit(@RequestBody BasMaterialCategory basMaterialCategory) {
		basMaterialCategoryService.updateBasMaterialCategory(basMaterialCategory);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "物料分类-通过id删除")
	@ApiOperation(value="物料分类-通过id删除", notes="物料分类-通过id删除")
	@DeleteMapping(value = "/delete")
	@CacheEvict(value= {CacheConstant.SYS_DICT_TABLE_CACHE,CacheConstant.BAS_MATERIAL_CATEGORY}, allEntries=true)
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		basMaterialCategoryService.deleteBasMaterialCategory(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "物料分类-批量删除")
	@ApiOperation(value="物料分类-批量删除", notes="物料分类-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@CacheEvict(value= {CacheConstant.SYS_DICT_TABLE_CACHE,CacheConstant.BAS_MATERIAL_CATEGORY}, allEntries=true)
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.basMaterialCategoryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "物料分类-通过id查询")
	@ApiOperation(value="物料分类-通过id查询", notes="物料分类-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BasMaterialCategory basMaterialCategory = basMaterialCategoryService.getById(id);
		if(basMaterialCategory==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(basMaterialCategory);
	}
	
	/**
	 * 通过id查询名称
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "物料分类-通过id查询名称")
	@ApiOperation(value="物料分类-通过id查询名称", notes="物料分类-通过id查询名称")
	@GetMapping(value = "/queryNameById")
	public Result<?> queryNameById(@RequestParam(name="id",required=true) String id) {
		BasMaterialCategory basMaterialCategory = basMaterialCategoryService.getById(id);
		if(basMaterialCategory==null) {
			return Result.error("未找到对应数据");
		}
		Map<String, String> map = Maps.newHashMap();
		map.put("name", basMaterialCategory.getName());
		String supplierId = basMaterialCategory.getSupplierId();
		if(StringUtils.isNotBlank(supplierId)) {
			BasSupplier supplier = this.supplierService.getById(supplierId);
			map.put("supplierId", supplierId);
			if(null != supplier) {
				map.put("supplierName", supplier.getName());
			} else {
				map.put("supplierName", "");
			}
		} else {
			map.put("supplierId", "");
			map.put("supplierName", "");
		}
		return Result.ok(map);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param basMaterialCategory
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasMaterialCategory basMaterialCategory) {
    	String title = "物料分类";
    	// Step.1 组装查询条件
        QueryWrapper<BasMaterialCategory> queryWrapper = QueryGenerator.initQueryWrapper(basMaterialCategory, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.orderByAsc("pid");
        // Step.2 获取导出数据
        List<BasMaterialCategory> pageList = basMaterialCategoryService.list(queryWrapper);
        List<BasMaterialCategory> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getTheId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }
        List<BasMaterialCategory> list = Lists.newArrayList();
        if(CollUtil.isNotEmpty(exportList)) {
        	for (BasMaterialCategory category : exportList) {
        		String hasChild = category.getHasChild();
        		if(null != hasChild && "1".equals(hasChild)) {
        			continue;
        		}
        		list.add(category);
			}
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, BasMaterialCategory.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }
    
    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, BasMaterialCategory.class);
    }

    /**
     * @Description 查询分类树
     * @return
     * Create at: 2020-08-26 15:31:58
     * @author: duanyong
     * Revision:
     *    2020-08-26 15:31:58 - first revision by duanyong
     *        
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	public Result<Map<String, Object>> queryTreeList(@RequestParam("type") String type) {
    	Result<Map<String, Object>> result = new Result<>();
    	LambdaQueryWrapper<BasMaterialCategory> wrapper = new LambdaQueryWrapper<>();
    	wrapper.eq(BasMaterialCategory::getIsEnabled, 1);
    	wrapper.orderByAsc(BasMaterialCategory::getPid);
    	//全部分类的ID集合
    	List<String> ids = new ArrayList<>();
    	List<BasMaterialCategory> list = this.basMaterialCategoryService.list(wrapper);
    	
    	for (BasMaterialCategory bmc : list) {
			ids.add(bmc.getId());
		}
    	
    	List<TreeModel> treeList = new ArrayList<>();
    	getTreeModelList(treeList, list, null, type);
    	
    	Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("treeList", treeList); // 全部树节点数据
		resMap.put("ids", ids);// 全部树ids
		result.setResult(resMap);
		result.setSuccess(true);
    	
		System.out.println(JSON.toJSON(resMap).toString());
    	return result;
    }
    
    /**
     * @Description 获取物料分类分类单位ID
     * @param categoryId
     * @return
     * Create at: 2020-10-13 17:36:27
     * @author: duanyong
     * Revision:
     *    2020-10-13 17:36:27 - first revision by duanyong
     *        
     */
    @GetMapping("/getCategoryUnitId")
    public Result<?> getCategoryUnitId(@RequestParam(name = "categoryId", required = true)String categoryId){
    	BasMaterialCategory category = this.basMaterialCategoryService.getById(categoryId);
    	String unitId = category.getUnitId();
    	
    	return Result.ok(unitId);
    }
    
	private void getTreeModelList(List<TreeModel> treeList, List<BasMaterialCategory> metaList, TreeModel temp, String type) {
		for (BasMaterialCategory category : metaList) {
			String pid = category.getPid();
			TreeModel tree = new TreeModel(category, type);
			if (temp == null && pid.equals("0")) {
				treeList.add(tree);
				if (!tree.getIsLeaf()) {
					getTreeModelList(treeList, metaList, tree, type);
				}
			} else if (temp != null && pid != null && pid.equals(temp.getKey())) {
				temp.getChildren().add(tree);
				if (!tree.getIsLeaf()) {
					getTreeModelList(treeList, metaList, tree, type);
				}
			}

		}
	}
	
	/**
	 * @Description 查询产品树
	 * @param type
	 * @return
	 * Create at: 2020-09-02 08:49:44
	 * @author: duanyong
	 * Revision:
	 *    2020-09-02 08:49:44 - first revision by duanyong
	 *        
	 */
	public Result<Map<String, Object>> queryProductTreeList(@RequestParam("type") String type) {
		Result<Map<String, Object>> result = new Result<>();
    	LambdaQueryWrapper<BasMaterialCategory> wrapper = new LambdaQueryWrapper<>();
    	wrapper.eq(BasMaterialCategory::getIsEnabled, 1);
    	wrapper.orderByAsc(BasMaterialCategory::getPid);
    	//全部分类的ID集合
    	List<String> ids = new ArrayList<>();
    	List<BasMaterialCategory> list = this.basMaterialCategoryService.list(wrapper);
    	
    	for (BasMaterialCategory bmc : list) {
			ids.add(bmc.getId());
		}
    	
    	List<TreeModel> treeList = new ArrayList<>();
    	getTreeModelList(treeList, list, null, type);
    	
    	Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("treeList", treeList); // 全部树节点数据
		resMap.put("ids", ids);// 全部树ids
		result.setResult(resMap);
		result.setSuccess(true);
    	
		System.out.println(JSON.toJSON(resMap).toString());
    	return result;
	}
	
	@PostMapping("/getCategory")
	public Result<?> getCategory(){
		return this.basMaterialCategoryService.getCategory();
	}
	
	@GetMapping("/getOrderCategory")
	public Result<?> getOrderCategory(@RequestParam("orderId")String orderId){
		return this.basMaterialCategoryService.getOrderCategory(orderId);
	}
	
	/**
	 * @Description 获取胶水的物料分类
	 * @return
	 * Create at: 2021-03-06 09:37:04
	 * @author: duany
	 * Revision:
	 *    2021-03-06 09:37:04 - first revision by duany
	 *        
	 */
	@GetMapping("/getGlueCategory")
	public Result<?> getGlueCategory(){
		return this.basMaterialCategoryService.getGlueCategory();
	}
	
	@GetMapping("/getCategoryName")
	public Result<?> getCategoryName(){
		return this.basMaterialCategoryService.getCategoryName();
	}
	
	@GetMapping("/getCategoryLabel")
	@ApiOperation(value="查询标签列表", notes="查询标签列表")
	@AutoLog(value = "物料分类-查询标签列表")
	public Result<List<BasCategoryLabel>> getCategoryLabel(String categoryId){
		return this.basMaterialCategoryService.getCategoryLabel(categoryId);
	}
	
	@PostMapping("/editCategoryLabel")
	@ApiOperation(value="维护物料标签", notes="维护物料标签")
	
	public Result<?> editCategoryLabel(@RequestBody CategoryLabelVO labelVO){
		return this.labelService.editCategoryLabel(labelVO);
	}
	
    /**
     * 获取对象ID
     *
     * @return
     */
    private <T> String getTheId(T item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
